package com.cnswhy.cloud.server.merchant.controller;

import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.TransType;
import com.cnswhy.cloud.server.common.entity.enumeration.WalletType;
import com.cnswhy.cloud.server.common.entity.mq.SpellFinishedMsg;
import com.cnswhy.cloud.server.common.entity.mq.SpreadLogMsg;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.service.*;
import com.cnswhy.cloud.server.core.service.customer.CustomerPrivilegeService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import com.cnswhy.cloud.server.merchant.dto.TestGetSumMoneyBySettDateAndTransTypeDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import static com.cnswhy.cloud.common.core.base.R.success;
import static com.cnswhy.cloud.common.core.context.BaseContextConstants.LOG_TRACE_ID;

@Slf4j
@RestController
public class TestController {
    @Autowired
    IdGeneratorService idGeneratorService;
    @Autowired
    WalletTransDtlService walletTransDtlService;
    @Autowired
    SpreadLogService spreadLogService;
    @Autowired
    WalletService walletService;
    @Autowired
    MessageService messageService;
    @Autowired
    CustomerService customerService;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    SpellInfoService spellInfoService;
/*
    @GetMapping("idGeneratorService")
    public R<String> idGeneratorService(){
        log.info("生成订单号");
        return success("生成订单号:" + idGeneratorService.genCommonIdString());
    }
    @GetMapping("dealWithDumplate")
    public R<String> dealWithDumplate(@RequestParam("ids[]") List<Long> ids,String flag){
        List<SpreadLog> spreadLogs = spreadLogService.listByIds(ids);
        for(SpreadLog spreadLog : spreadLogs){
            Customer customer = customerService.getById(spreadLog.getCustomerId());
            CustomerWallet customerWallet = walletService.checkAndCreate(customer.getId(), WalletType.LOVE_BALANCE, CnswhyUtil.getFen(customer.getLoveBalance()));
            walletService.ded(customerWallet.getCustomerId(),WalletType.LOVE_BALANCE,TransType.LOVE_BALANCE_RECYCLE,CnswhyUtil.getFen(spreadLog.getAmount()),TransType.LOVE_BALANCE_RECYCLE + spreadLog.getOrderNum() + flag);
        }
        return success("成功");
    }
    @GetMapping("recycle")
    public R<String> recycle(){
        List<TransType> transTypes = new ArrayList<>();
        transTypes.add(TransType.CONTRIBUTION_BALANCE_CHARGE);
        transTypes.add(TransType.LOVE_BALANCE_CHARGE);
        transTypes.add(TransType.SHARE_CHARGE);
        List<String> settDate = new ArrayList<>();
        settDate.add("20201018");
        settDate.add("20201019");
        List<WalletTransDtl> walletTransDtlList = walletTransDtlService.list(Wraps.<WalletTransDtl>lbQ().in(WalletTransDtl::getTransType,transTypes).in(WalletTransDtl::getSettDate,settDate));
        for(WalletTransDtl walletTransDtl : walletTransDtlList){
            CustomerWallet customerWallet = customerWalletService.getById(walletTransDtl.getCustomerWalletId());
            walletService.ded(customerWallet.getCustomerId(),customerWallet.getWalletType(),TransType.RECYCLE,walletTransDtl.getDedBal(),TransType.RECYCLE + idGeneratorService.genCommonIdString());
        }
        List<SpellInfo> spellInfos = spellInfoService.list(Wraps.<SpellInfo>lbQ().gt(SpellInfo::getId,20291205059000046L));
        for(SpellInfo spellInfo : spellInfos){
            SpellFinishedMsg spellFinishedMsg = SpellFinishedMsg.builder()
                    .spellOrderId(spellInfo.getOrderNum())
                    .spellId(spellInfo.getId())
                    .spellPriceId(spellInfo.getPriceId()).build();
            spellFinishedMsg.setTraceId(MDC.get(LOG_TRACE_ID));
            messageService.sendQueueByObject(AmqpExchange.SPELL_FINISHED_MESSAGE,spellFinishedMsg);
        }

        return success("成功");
    }
    @GetMapping("syncSpreadLog")
    public R<String> syncSpreadLog(){
        log.info("syncSpreadLog");
        List<WalletTransDtl> walletTransDtls = walletTransDtlService.list();
        for(WalletTransDtl walletTransDtl : walletTransDtls){
            SpreadLogMsg spreadLog = SpreadLogMsg.builder()
                    .id(walletTransDtl.getId()).build();
            spreadLog.setTraceId(MDCUtil.getTraceId());
            messageService.sendQueueByObject(AmqpExchange.SPREAD_MESSAGE, spreadLog);
        }
        return success("成功");
    }
    @Autowired
    CustomerPrivilegeService customerPrivilegeService;
    @GetMapping("repairPrivilege")
    public R<String> repairPrivilege(){
        log.info("repairPrivilege");
        List<String> settDate = new ArrayList<>();
        settDate.add("20201018");
        settDate.add("20201019");
        //select customer_id from t_spell_order where sett_date in ('20201018','20201019') and pay_type = 1 and status != 5
        List<SpellOrder> spellOrders = spellOrderService.list(Wraps.<SpellOrder>lbQ().eq(SpellOrder::getPayType,1).ne(SpellOrder::getStatus,5).in(SpellOrder::getSettDate,settDate));
        List<WalletTransDtl> walletTransDtls = walletTransDtlService.list();
        for(SpellOrder spellOrder : spellOrders){
            List<CustomerPrivilege> query = customerPrivilegeService.queryCustomerPrivilegeList(spellOrder.getPriceId(),spellOrder.getCustomerId());
            if(query.size() > 0){
                CustomerPrivilege customerPrivilege = query.get(0);
                customerPrivilege.setUsedNum(customerPrivilege.getUsedNum() - 1);
                customerPrivilegeService.updateById(customerPrivilege);
            }
        }
        return success("成功");
    }
    @Autowired
    RedisService redisService;
    @Autowired
    SpellOrderService spellOrderService;
    @Autowired
    SpellReportService spellReportService;
    @GetMapping("rebuildReport")
    public R<String> rebuildReport(){
        log.info("syncSpreadLog");
        log.error("======================开始处理平台收益报表");
        BigDecimal totalMoney = spellOrderService.queryTodaySpellSuccessMoney();
        String backRate = (String)redisService.hget(RedisConstant.SYS_CONFIG_2, RedisConstant.BUY_BACK_PRICE);
        BigDecimal costMoney = totalMoney.multiply(new BigDecimal(backRate)).setScale(2, BigDecimal.ROUND_DOWN);
        //爱心收益
        Long loveMoney = walletTransDtlService.getSumMoneyBySettDateAndTransType(SystemClockUtil.getSettDateyyyyMMdd(),TransType.LOVE_BALANCE_CHARGE);
        //贡献收益
        Long contributionMoney = walletTransDtlService.getSumMoneyBySettDateAndTransType(SystemClockUtil.getSettDateyyyyMMdd(),TransType.CONTRIBUTION);
        //拼团收益
        Long spellMoney = walletTransDtlService.getSumMoneyBySettDateAndTransType(SystemClockUtil.getSettDateyyyyMMdd(),TransType.SPELL_BALANCE_CHARGE);
        SpellReport report = new SpellReport();
        report = spellReportService.getOne(Wraps.<SpellReport>lbQ().eq(SpellReport::getSettDate,SystemClockUtil.getSettDateyyyyMMdd()));
        spellReportService.removeById(report);
        report = new SpellReport();
        report.setTotalMoney(totalMoney);
        report.setCostMoney(costMoney);
        report.setLoveMoney(CnswhyUtil.getMoney(loveMoney));
        report.setContributionMoney(CnswhyUtil.getMoney(contributionMoney));
        report.setSpellMoney(CnswhyUtil.getMoney(spellMoney));
        report.setSettDate(SystemClockUtil.getSettDateyyyyMMdd());
        spellReportService.save(report);
        return success("成功");
    }*/
    @GetMapping("getSumMoneyBySettDateAndTransType")
    public R<Long> getSumMoneyBySettDateAndTransType(TestGetSumMoneyBySettDateAndTransTypeDTO testGetSumMoneyBySettDateAndTransTypeDTO){
        log.info("生成订单号");
        return success(walletTransDtlService.getSumMoneyBySettDateAndTransType(testGetSumMoneyBySettDateAndTransTypeDTO.getSettDate(),testGetSumMoneyBySettDateAndTransTypeDTO.getTransType()));
    }
}
